package com.jie.eclipse.pan.popup.actions;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.IPageChangedListener;
import org.eclipse.jface.dialogs.IPageChangingListener;
import org.eclipse.jface.dialogs.PageChangedEvent;
import org.eclipse.jface.dialogs.PageChangingEvent;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.TreeSelection;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IActionDelegate;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;

import com.jie.eclipse.pan.Activator;
import com.jie.eclipse.pan.dao.QMDao;
import com.jie.eclipse.pan.popup.wizard.BaseWizard;
import com.jie.eclipse.pan.popup.wizard.CreatePageTemplateWizard;
import com.jie.eclipse.pan.popup.wizardpage.BasePage;

public class NewPageAction implements IObjectActionDelegate {

	private Shell shell;
	private IWorkbenchPart targetPart;
	
	/**
	 * Constructor for Action1.
	 */
	public NewPageAction() {
		super();
	}

	/**
	 * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart)
	 */
	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
		shell = targetPart.getSite().getShell();
		this.targetPart = targetPart;
		
	}

	/**
	 * @see IActionDelegate#run(IAction)
	 */
	public void run(IAction action) {
		QMDao.getInstance().setStore(Activator.getDefault().getPreferenceStore());
		ISelection selection = targetPart.getSite().getSelectionProvider().getSelection();
		if(selection instanceof TreeSelection){
			IFolder folder = null;
			Object obj = ((TreeSelection)selection).getFirstElement();
			if(obj instanceof IFolder || (obj instanceof IFile && ((IFile)obj).getParent() instanceof IFolder )){
				if(obj instanceof IFolder){
					folder = (IFolder)obj;
				}else{
					folder = (IFolder)((IFile)obj).getParent();
				}
				 
			 	BaseWizard wizard = new CreatePageTemplateWizard();
			 	wizard.setCurrFolder(folder);
			 	
				WizardDialog dlg = new WizardDialog(shell,wizard);
				dlg.addPageChangedListener(new IPageChangedListener() {
					public void pageChanged(PageChangedEvent event) {
						BasePage page = (BasePage) event.getSelectedPage();
						page.reloadPageConfig();
					}
				});
				
				dlg.addPageChangingListener(new IPageChangingListener() {
					public void handlePageChanging(PageChangingEvent event) {
						
						BasePage page = (BasePage) event.getCurrentPage();
						page.reloadPageConfig();
					}
				});
				dlg.setPageSize(900, 620);//设置向导页面的大小
			    dlg.open();
			}
		}
	}

	/**
	 * @see IActionDelegate#selectionChanged(IAction, ISelection)
	 */
	public void selectionChanged(IAction action, ISelection selection) {
	}
}
